package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

public class Flink02_KeyedState_ListState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.使用map将度过来的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> result = streamSource.map(
                new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //4.将相同ID的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = result.keyBy("id");

        //TODO 5.针对每个传感器输出最高的3个水位值
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            //TODO a.定义状态
            private ListState<Integer> listState;


            //TODO b.初始化状态
            @Override
            public void open(Configuration parameters) throws Exception {
                listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("list-state", Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.将当前水位保存至状态中
                listState.add(value.getVc());

                //2.取出状态中数据做排序，由大到小排序
                Iterable<Integer> iterVc = listState.get();

                //3.将迭代器中的数据遍历出来存入list做排序
                ArrayList<Integer> listVc = new ArrayList<>();
                for (Integer vc : iterVc) {
                    listVc.add(vc);
                }

                //4.排序
                listVc.sort(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o2-o1;
                    }
                });

                //5.取出集合中最高的三个水位 （完整版）
                if (listVc.size()>3){
                    listVc.remove(3);
                }

                //6.更新状态
                listState.update(listVc);
                out.collect(listVc.toString());


                //或者 （不完整版）
//                Integer firstVc;
//                Integer secondeVc;
//                Integer thirdVc;
//                if (listVc.size()>3){
//                 Integer  firstVc = listVc.get(0);
//                    Integer  secondeVc = listVc.get(1);
//                    Integer  thirdVc = listVc.get(2);
//                    //更新状态
//                 out.collect(listVc.get(0).toString());
//                 out.collect(listVc.get(1).toString());
//                 out.collect(listVc.get(2).toString());
//
//                }else {
//                   out.collect(listVc.toString());
//                }

            }
        }).print();

        env.execute();
    }

}
